/*
 * @Author: 糊涂的老知青
 * @Date: 2022-08-21
 * @Version: 1.0.0
 * @Description:
 */
package tenant_domainservice

import (
	"lzq-admin/base/domainconsts"
	"lzq-admin/base/domainservice"
	tenant_model "lzq-admin/internal/tenant/model"
	"lzq-admin/pkg/orm"
	"lzq-admin/pkg/utility"

	"github.com/gin-gonic/gin"
	"github.com/goinggo/mapstructure"
	"github.com/pkg/errors"
)

// TenantDomainService 租户领域服务
type TenantDomainService struct {
	domainservice.BaseDomainService
}

func NewDSTenant(c *gin.Context) *TenantDomainService {
	return &TenantDomainService{
		domainservice.BaseDomainService{
			GinCtx: c,
		},
	}
}

func (t *TenantDomainService) Insert(modelDto tenant_model.CreateTenantDto) (result tenant_model.Tenant, err error) {
	var entity tenant_model.Tenant
	var exist bool
	lzqOrm := orm.NewLzqOrm(t.GinCtx)
	exist, err = lzqOrm.QSession(false).Exist(&tenant_model.Tenant{Code: modelDto.Code})
	if err != nil {
		return entity, err
	}
	if exist {
		return entity, errors.New("租户编码：" + modelDto.Code + " 已存在，请更换租户编码")
	}

	resultMap := utility.StructToMap(modelDto, false)
	if err = mapstructure.Decode(resultMap, &entity); err != nil {
		return entity, err
	}
	entity.ID = utility.UuidCreate()
	entity.Status = domainconsts.TenantStatusEnable

	_, err = lzqOrm.ISession().Insert(&entity)
	return entity, err
}
